package com.siyoumi.app.sys.wx_open;

import cn.hutool.core.util.XmlUtil;
import com.siyoumi.app.sys.service.wx_center.CenterHandler;
import com.siyoumi.app.sys.service.wx_center.common_handle.CenterHandleDecXmlAndCheckSign;
import com.siyoumi.component.XRedis;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.ApiController;
import com.siyoumi.entity.SysAccsuperConfig;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.service.SysAccsuperConfigService;
import com.siyoumi.util.XJson;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

//用于接收平台推送给第三方平台账号的消息与事件，如授权事件通知、component_verify_ticket
@Slf4j
@RestController
@RequestMapping("/wx_open/server/notify")
public class WxOpenNotify
        extends ApiController {
    @RequestMapping()
    public Object index(@RequestBody(required = false) String xmlStr) {

        InputData inputData = InputData.fromRequest();
        log.info(XJson.toJSONString(inputData));
        log.info(xmlStr);

        if (XStr.isNullOrEmpty(xmlStr)) {
            XValidator.err(EnumSys.MISS_VAL.getR("miss xml"));
        }

        Map<String, Object> xmlEncMap = XmlUtil.xmlToMap(xmlStr);
        String appid = (String) xmlEncMap.get("AppId");
        String messageEncrypt = (String) xmlEncMap.get("Encrypt");

        SysAccsuperConfig entityConfig = SysAccsuperConfigService.getBean().getXConfigByAppId(appid);
        if (entityConfig == null) {
            XValidator.err(EnumSys.ERR_VAL.getR("app_id未配置, " + appid));
        }

        //检查签名
        CenterHandleDecXmlAndCheckSign.checkSign(messageEncrypt, entityConfig.getKey());

        //企业微信需要对内容进行解密
        String xml = CenterHandler.getInstance(entityConfig.getKey()).decryptTxt(messageEncrypt);

        Map<String, Object> xmlMap = XmlUtil.xmlToMap(xml);
        String infoType = (String) xmlMap.get("InfoType");
        log.debug("xml: {}", xml);
        log.debug("infoType: {}", infoType);
        if ("component_verify_ticket".equals(infoType)) {
            String componentVerifyTicket = (String) xmlMap.get("ComponentVerifyTicket");

            SysAccsuperConfig entityConfigUpdate = new SysAccsuperConfig();
            entityConfigUpdate.setAconfig_id(entityConfig.getAconfig_id());
            entityConfigUpdate.setAconfig_js_ticket(componentVerifyTicket);
            SysAccsuperConfigService.getBean().saveOrUpdatePassEqualField(entityConfig, entityConfigUpdate);
            XRedis.getBean().del(SysAccsuperConfigService.getBean().getEntityCacheKey(entityConfig.getAconfig_id()));
        }

        return "success";
    }
}
